package com.hmyd.hmyd_android.ui;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.Bank;
import com.hmyd.hmyd_android.dto.BankCard;
import com.hmyd.hmyd_android.dto.Binding;
import com.hmyd.hmyd_android.dto.SinaDetail;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.hmyd.hmyd_android.view.WheelCityPopupwindow;
import com.hmyd.hmyd_android.view.WheelPopupListener;
import com.hmyd.hmyd_android.view.WheelPopupwindow;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 银行卡绑定
 */
@ContentView(R.layout.activity_bind_bank_card)
public class BindBankCardActivity extends BasicActivity implements OnFocusChangeListener {
	@ViewInject(R.id.home_title)
	public View home_title;
	@ViewInject(R.id.home_title_txt)
	public TextView home_title_txt;
	@ViewInject(R.id.home_right)
	public TextView home_right;
	
	private WheelCityPopupwindow mWheelCityPopupwindow;
	private WheelPopupwindow mWheelPopupwindow;
	
	@ViewInject(R.id.root)
	private View mRoot;
	@ViewInject(R.id.realName)
	private TextView realName;
	@ViewInject(R.id.et_bank)
	private EditText mEtBank;
	@ViewInject(R.id.bankAccountNo)
	private EditText bankAccountNo;
	@ViewInject(R.id.et_bank_city)
	private EditText et_bank_city;
	@ViewInject(R.id.phone)
	private EditText phone;
	
	@ViewInject(R.id.et_code)
	private EditText et_code;
	@ViewInject(R.id.btn_get_code)
	private Button btn_get_code;
	
	@ViewInject(R.id.save)
	private Button mSave;
	
	private static String SER_KEY = "SER_KEY";
	BankCard bankCard;
	
	private final int BINDING = 0;
	private final int BINDINGADVANCE = 1;
	private final int BANKCARD = 2;
	private final int GETSINAPASSWORD = 3;
	
	private String requestNo;
	
	public static Intent getIntent(Context context,BankCard bankCard){
		Intent intent = new Intent(context, BindBankCardActivity.class);
		Bundle mBundle = new Bundle();  
        mBundle.putSerializable(SER_KEY,bankCard);
		intent.putExtras(mBundle);
		
		return intent;
	}
	
	private void onRequest(){
		onRequest(BANKCARD, UrlConstant.BANKCARD, HttpMethod.POST, null);
	}
	
	/*private TextWatcher watcher = new TextWatcher() {
        
        @Override    
        public void afterTextChanged(Editable s) {
        }   
          
        @Override 
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }  
 
         @Override    
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        	 codePatterns();
        }                    
    };
    
    private TextWatcher code_watcher = new TextWatcher() {
        
        @Override    
        public void afterTextChanged(Editable s) {
        }   
          
        @Override 
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }  
 
         @Override    
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        	 if(!TextUtils.isEmpty(et_code.getText().toString().trim())
        			 && !TextUtils.isEmpty(requestNo)){
        		 mSave.setEnabled(true);
        	 }else{
        		 mSave.setEnabled(false);
        	 }
        }                    
    };
  */  
   /* private void codePatterns(){
    	if(!TextUtils.isEmpty(mEtBank.getText().toString().trim())
    		&&!TextUtils.isEmpty(bankAccountNo.getText().toString().trim())
    		&&!TextUtils.isEmpty(et_bank_city.getText().toString().trim())
    		&&!TextUtils.isEmpty(phone.getText().toString().trim())
    		&&!TextUtils.isEmpty(phone.getText().toString().trim()) 
    		&&RegPatterns.MobilePattern.matcher(phone.getText().toString()).matches()){
    		btn_get_code.setEnabled(true);
    	}else{
    		btn_get_code.setEnabled(false);
    	}
    }*/
	
    String province;
	String city;
	String bankCode;
    
	private WheelPopupListener wheelBankPopupListener = new WheelPopupListener() {
		@Override
		public void getSecondString(int index) {
			
		}
		
		@Override
		public void getFirstString(int index) {
			mEtBank.setText(bankCard.cards.get(index).name);
			
			bankCode = bankCard.cards.get(index).code;
		}

		@Override
		public void getFirstString(String name) {
			
		}

		@Override
		public void getSecondString(String name) {
			
		}
	};
	
	private WheelPopupListener wheelCityPopupListener = new WheelPopupListener() {
		@Override
		public void getSecondString(int index) {
			
		}
		
		@Override
		public void getFirstString(int index) {
			
		}

		@Override
		public void getFirstString(String name) {
			et_bank_city.setText(name);
			province = name;
		}

		@Override
		public void getSecondString(String name) {
			et_bank_city.setText(et_bank_city.getText().toString()+" "+name);
			city = name;
		}
	};
	
	@OnClick({R.id.et_bank, R.id.et_bank_city, R.id.btn_get_code, R.id.save})
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.et_bank:
				mWheelCityPopupwindow.showAtLocation(mRoot, Gravity.BOTTOM, 0, 0);
				Utils.closeBoard(this);
				break;
			case R.id.et_bank_city:
				mWheelPopupwindow.showAtLocation(mRoot, Gravity.BOTTOM, 0, 0);
				Utils.closeBoard(this);
				break;
			case R.id.btn_get_code:
				// 信息判断
				if (TextUtils.isEmpty(realName.getText().toString().trim()) || 
						TextUtils.isEmpty(bankAccountNo.getText().toString().trim()) ||
						TextUtils.isEmpty(phone.getText().toString().trim())) {
					MyToast.showHMToast(this, false, getString(R.string.complemented_info));
					return;
				}
				
				getCode();
				
				break;
			case R.id.save:
				RequestParams params2 = new RequestParams();
				params2.addBodyParameter("requestNo", requestNo);
				params2.addBodyParameter("validCode", et_code.getText().toString().trim());
				
				onRequest(BINDINGADVANCE, UrlConstant.BINDINGADVANCE, HttpMethod.POST, params2);
				
				break;
		default:
			break;
		}
	}
	
	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
			case BINDING:
				java.lang.reflect.Type type2 = new TypeToken<Binding>() {}.getType();
				Binding binding = gson.fromJson(result, type2);
				
				requestNo = binding.requestNo;
				
				MyToast.showToast(this, "验证码已发送，请注意查收");
				
				handler.postDelayed(runnable, 0);
				
				setSaveBg(true);
				break;
				
			case BINDINGADVANCE:
				
				java.lang.reflect.Type type3 = new TypeToken<Bank>() {}.getType();
				Bank bank = gson.fromJson(result, type3);
				MyToast.showToast(this, bank.message);
//				AppBasic.getInstance().finishCurrentActivity();
				
				if (bank.isSuccess) {
					onRequest(GETSINAPASSWORD, UrlConstant.GETSINAPASSWORD, HttpMethod.GET, null);
				}
				
				break;
			case BANKCARD:
				java.lang.reflect.Type type4 = new TypeToken<BankCard>() {}.getType();
				bankCard = gson.fromJson(result, type4);
				if (null != bankCard) {
					setData(bankCard);
				} else {
					AppBasic.getInstance().finishActivity(this);
				}
				break;
			case GETSINAPASSWORD:
				java.lang.reflect.Type type5 = new TypeToken<SinaDetail>() {}.getType();
				SinaDetail detail = gson.fromJson(result, type5);
				if (null == detail) return;

				if (detail.code.equalsIgnoreCase("SUCCESS")) {
					Utils.jumpURL(this, detail.message, "设置新浪账户密码", "", false);
					AppBasic.getInstance().finishCurrentActivity();
				}
				break;
			default:
				break;
		}
	}
	
	@Override
	public void onPostFailure(int postId, String msg) {
		switch (postId) {
		case BINDINGADVANCE:
			MyToast.showToast(this, "绑卡失败，详情请联系客服人员！");
			
			setSaveBg(true);
			break;

		default:
			break;
		}
	}
	
	/**
	 * 获取验证码
	 */
	private void getCode(){
		secs = 60;		// 设置获取验证码的有效时间
		
		RequestParams params = new RequestParams();
		params.addBodyParameter("accountName", realName.getText().toString().trim());
		params.addBodyParameter("bankCode", bankCode);
		params.addBodyParameter("bankAccountNo", bankAccountNo.getText().toString().trim());
		params.addBodyParameter("province", province);
		params.addBodyParameter("city", city);
		params.addBodyParameter("phoneNo", phone.getText().toString().trim());
		
		onRequest(BINDING, UrlConstant.BINDING, HttpMethod.POST, params);
	}
	
	/**
	 * 验证码有效期
	 */
	Runnable runnable = new Runnable() {
		
		@Override
		public void run() {
			secs--;
			if (secs > 0) {
				btn_get_code.setText("剩余" + secs + "秒");
				setVerificationCodeBg(true);
			} else {
				btn_get_code.setText("重新获取");
				setVerificationCodeBg(false);
			}
			
			handler.postDelayed(this, 1000);
		}
		
	};
	
	/**
	 * 设置验证码背景
	 */
	@SuppressWarnings("deprecation")
	private void setVerificationCodeBg(boolean isPressed){
		if (isPressed) {
			btn_get_code.setEnabled(false);
			btn_get_code.setTextColor(getResources().getColor(R.color.white));
			btn_get_code.setBackgroundColor(getResources().getColor(R.color.code_pressed_bg));
		} else {
			btn_get_code.setEnabled(true);
			btn_get_code.setTextColor(getResources().getColor(R.color.text_orange));
			btn_get_code.setBackgroundDrawable(getResources().getDrawable(R.drawable.recharge_shape_selector));
		}
	}
	
	private int secs;	// 短信信息倒计时
	private CodeHandler handler = new CodeHandler(this);
	static class CodeHandler extends Handler {
		WeakReference<Context> reference;
		
		public CodeHandler(Context context){
			reference = new WeakReference<Context>(context);
		}
		
		@Override
		public void handleMessage(Message msg) {
		}
	}
	
	/**
	 * 设置提交按钮背景
	 */
	@SuppressWarnings("deprecation")
	private void setSaveBg(boolean isPressed){
		if (isPressed) {
			mSave.setEnabled(true);
			mSave.setBackgroundDrawable(getResources().getDrawable(R.drawable.recharge_shape_pressed));
		} else {
			mSave.setEnabled(false);
			mSave.setBackgroundColor(getResources().getColor(R.color.code_pressed_bg));
		}
	}
	 
	@Override
	protected void onDestroy() {
		super.onDestroy();

		handler.removeCallbacksAndMessages(null);
    }

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		switch (v.getId()) {
		case R.id.et_bank:
			if(hasFocus){
				mWheelCityPopupwindow.showAtLocation(mRoot, Gravity.BOTTOM, 0, 0);
				Utils.closeBoard(this);
			}
			break;
		case R.id.et_bank_city:
			if(hasFocus){
				mWheelPopupwindow.showAtLocation(mRoot, Gravity.BOTTOM, 0, 0);
				Utils.closeBoard(this);
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void setParams() {
		home_title_txt.setText(getString(R.string.bind_bankcard));
		home_title.setOnTouchListener(touch);
		
		mEtBank.setKeyListener(null);
		mEtBank.setOnFocusChangeListener(this);
		
		et_bank_city.setKeyListener(null);
		et_bank_city.setOnFocusChangeListener(this);
		
		setSaveBg(false);
		
		bankCard = (BankCard)getIntent().getSerializableExtra(SER_KEY);
		if(bankCard==null){
			onRequest();
		} else {
			setData(bankCard);
		}
	}
	
	private void setData(BankCard bankcard){
		realName.setText(bankCard.data.realName);
//		mEtBank.addTextChangedListener(watcher);
//		bankAccountNo.addTextChangedListener(watcher);
//		et_bank_city.addTextChangedListener(watcher);
//		phone.addTextChangedListener(watcher);
//		et_code.addTextChangedListener(code_watcher);
		
		String[] bankArr = new String[bankCard.cards.size()];
		for(int i=0;i<bankCard.cards.size();i++){
			bankArr[i] = bankCard.cards.get(i).name;
		}
		mWheelCityPopupwindow = new WheelCityPopupwindow(this, wheelBankPopupListener, 0, 0,bankArr);
		mWheelPopupwindow = new WheelPopupwindow(this, wheelCityPopupListener, 0, 0);
		
		//设置默认获取焦点  
		mWheelCityPopupwindow.setFocusable(true);
		mWheelPopupwindow.setFocusable(true);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		
	}

}
